package cn.edu.ctbu.service.impl;

import cn.edu.ctbu.entity.AddressBook;
import cn.edu.ctbu.mapper.AddressBookMapper;
import cn.edu.ctbu.service.IAddressBookService;
import cn.edu.ctbu.utils.JWTUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 地址簿 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-12
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Autowired
    HttpServletRequest httpServletRequest;
    @Override
    public List<AddressBook> get() {
        //获得userid
        String token = httpServletRequest.getHeader("Authorization");
        Claims claims = JWTUtils.parseJWT(token);
        Long id = claims.get("id", Long.class);

        //获得地址
        QueryWrapper wrapper=new QueryWrapper<>().eq("user_id",id);
        List<AddressBook> list = list(wrapper);
        return list;
    }

    @Override
    public void putDefault(Long id) {
        //获得userid
        String token = httpServletRequest.getHeader("Authorization");
        Claims claims = JWTUtils.parseJWT(token);
        Long userid = claims.get("id", Long.class);

        UpdateWrapper wrapper=new UpdateWrapper<>().eq("user_id",userid)
                .set("is_default",0);
        update(wrapper);
        UpdateWrapper wrapper1=new UpdateWrapper<>().eq("id",id).set("is_default",1);
        update(wrapper1);
    }

    @Override
    public AddressBook getdefault(Long addressId) {
        //获得userid
        String token = httpServletRequest.getHeader("Authorization");
        Claims claims = JWTUtils.parseJWT(token);
        Long userid = claims.get("id", Long.class);

        if (addressId!=0){
            AddressBook byId = getById(addressId);
            return byId;

        }else {
            QueryWrapper wrapper = new QueryWrapper<>().eq("user_id", userid).eq("is_default", 1);
            AddressBook one = getOne(wrapper);
            return one;
        }
    }

    @Override
    public void put(AddressBook dto) {
        //获得userid
        String token = httpServletRequest.getHeader("Authorization");
        Claims claims = JWTUtils.parseJWT(token);
        Long userid = claims.get("id", Long.class);

        if (dto.getIsDefault()){
            UpdateWrapper wrapper=new UpdateWrapper<>().eq("user_id",userid).set("is_default",0);
            update(wrapper);
        }
        dto.setUserId(userid);
        if (dto.getId()!=null){
            updateById(dto);
        }else{
            save(dto);
        }


    }
}
